package com.xxx.springboot.controller;

import cn.hutool.extra.qrcode.QrCodeUtil;
import com.xxx.springboot.service.UserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 二维码扫码登录 Controller
 */
@Controller
@RequestMapping(value = "/", produces = "application/json;charset=utf-8")
public class LoginController extends BaseController {

    private static final Logger logger = LoggerFactory.getLogger(DemoController.class);

    @Resource
    private UserService userService;

    @RequestMapping("/login")
    public String login(){
        return "qr_login";
    }

    //获取登录二维码、放入Token
    @RequestMapping(value = "/getLoginQr" ,method = RequestMethod.GET)
    public void createCodeImg(HttpServletRequest request, HttpServletResponse response){
        response.setHeader("Pragma", "No-cache");
        response.setHeader("Cache-Control", "no-cache");

        response.setDateHeader("Expires", 0);
        response.setContentType("image/jpeg");

        try {
            //这里没啥操作 就是生成一个UUID插入 数据库的表里
            String uuid = userService.createQrImg();
            response.setHeader("uuid", uuid);
            // 这里是开源工具类 hutool里的QrCodeUtil
            // 网址：http://hutool.mydoc.io/
            QrCodeUtil.generate(uuid, 300, 300, "jpg",response.getOutputStream());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 确认身份接口：确定身份以及判断是否二维码过期等
     * @param token
     * @param userId
     * @return
     */
    @RequestMapping(value = "/bindUserIdAndToken" ,method = RequestMethod.GET)
    @ResponseBody
    public Object bindUserIdAndToken(@RequestParam("token") String token ,
                                     @RequestParam("userId") Integer userId,
                                     @RequestParam(required = false,value = "projId") Integer projId){
        try {
            return userService.bindUserIdAndToken(userId, token, projId);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "null";
    }

}
